﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Web.UI.WebControls;
using OTE.Infrastructure.ConfirgurationEngine;
using OTE.Infrastructure.Extensions;
using OTE.Tasks.Commands.Question;
using OTE.Web.Infrastructure;
using OTE.Web.Infrastructure.TabMenu;
using OTE.Web.Infrastructure.Utils;
using OTE.Web.Mvc.Queries.Category;
using OTE.Web.Mvc.Queries.Question;
using OTE.Web.Mvc.ViewModels.Question;

namespace OTE.Web.Mvc.Areas.Admin.Controllers
{
    public class QuestionController : OTEController
    {
        public IQuestionQuery QuestionQuery { get; private set; }

        public IConfigurator Configurator { get; private set; }

        public ICategoryQuery CategoryQuery { get; private set; }

        public ICategoryQuery CategoryListQuery { get; private set; }

        public QuestionController(IQuestionQuery questionQuery, IConfigurator configurator, ICategoryQuery allCategoryQuery, ICategoryQuery categoryListQuery)
        {
            QuestionQuery = questionQuery;
            Configurator = configurator;
            CategoryQuery = allCategoryQuery;
            CategoryListQuery = categoryListQuery;
        }

        #region action

        #region public ActionResult Index()

        /// <summary>
        ///
        /// </summary>
        /// <param name="id">id is pageIndex</param>
        /// <returns></returns>
        public ActionResult Index(int? id)
        {
            var pageSize = Configurator.GetAppSettingString("PageSize").ToInterger();

            QuestionListViewModel viewModel;
            if (id == null)
                viewModel = Paging(1, pageSize);
            else
                viewModel = Paging((int)id, pageSize);

            return View(viewModel);
        }

        #endregion public ActionResult Index()

        #region Create()

        public ActionResult Create()
        {
            var viewModel = new QuestionInformationViewModel();

            var allCategory = CategoryQuery.GetCategoryParent();
            viewModel.Categories = allCategory.ToList();

            return View(viewModel);
        }

        [HttpPost]
        public ActionResult Create(QuestionInformationViewModel viewModel)
        {
            var command = new QuestionMetaDataAddedCommand
            {
                CategoryId = viewModel.CatSelectedId,
                CreatedBy = User != null ? User.Identity.Name : string.Empty,
                Content = viewModel.Content,
                //need to replace user id
                UserId = 1 // TODO: remove hardcode here, very dangerous if dont have the user with id 1
            };

            var result = CommandProcessor.Process(command);

            return RedirectToAction("Index");
        }

        #endregion Create()

        #region Update()

        public ActionResult Update(int id)
        {
            var question = QuestionQuery.GetQuestionById(id);

            var viewModel = new UpdateQuestionViewModel();

            viewModel.CatSelectedId = question.CategoryId;
            viewModel.Content = question.Content;
            viewModel.Id = question.Id;

            var allCategory = CategoryQuery.GetCategoryParent();
            viewModel.ParentCategories = allCategory.ToList();

            //get category
            var category = CategoryListQuery.GetCategoryById(question.CategoryId);

            if (category.ParentId > 0)
            {
                viewModel.ParentCatId = category.ParentId;
                viewModel.ChildCatId = category.Id;
            }
            else
            {
                viewModel.ParentCatId = category.Id;
            }
            viewModel.ChildCategories = CategoryQuery.GetChildCategory(viewModel.ParentCatId).ToList();

            return View(viewModel);
        }

        [HttpPost]
        public ActionResult Update(UpdateQuestionViewModel viewModel)
        {
            TryUpdateModel(viewModel);

            var command = new QuestionMetaDataUpdatedCommand()
            {
                CategoryId = viewModel.CatSelectedId,
                Content = viewModel.Content,
                Id = viewModel.Id,
                ModifiedBy = User != null ? User.Identity.Name : string.Empty
            };

            var result = CommandProcessor.Process(command);

            return RedirectToAction("Index");
        }

        #endregion Update()

        #region Delete

        #region public ActionResult Delete(int id)

        public ActionResult Delete(int id)
        {
            var command = new QuestionMetaDataDeletedCommand()
            {
                Ids = new int[] { id }
            };

            var result = CommandProcessor.Process(command);
            return RedirectToAction("Index");
        }

        #endregion public ActionResult Delete(int id)

        #region public ActionResult DeleteAll(string id)

        public ActionResult DeleteAll(string id)
        {
            string[] arrId = id.Split(',');

            List<int> lst = new List<int>();

            int i;

            var command = new QuestionMetaDataDeletedCommand();

            for (i = 0; i < arrId.Length; i++)
                lst.Add(Convert.ToInt32(arrId[i]));

            command.Ids = lst.ToArray();

            var result = CommandProcessor.Process(command);

            return RedirectToAction("Index");
        }

        #endregion public ActionResult DeleteAll(string id)

        #endregion Delete

        #region public JsonResult GetChildCategory(int id)

        /// <summary>
        ///
        /// </summary>
        /// <param name="id">parent id</param>
        /// <returns></returns>
        public JsonResult GetChildCategory(int id)
        {
            var childList = CategoryQuery.GetChildCategory(id);

            List<ListItem> list = new List<ListItem>();

            list.Add(new ListItem() { Value = "", Text = "" });

            foreach (var categoryDto in childList)
            {
                list.Add(new ListItem() { Value = categoryDto.Id.ToString(), Text = categoryDto.Name });
            }

            return this.Json(list, JsonRequestBehavior.AllowGet);
        }

        #endregion public JsonResult GetChildCategory(int id)

        #endregion action

        #region private

        #region private static CreateQuestionViewModel GetCreateQuestionViewModel()

        [NonAction]
        private static CreateQuestionViewModel GetCreateQuestionViewModel()
        {
            return new CreateQuestionViewModel();
        }

        #endregion private static CreateQuestionViewModel GetCreateQuestionViewModel()

        #region private List<MenuModel> GetMenuItems(int? topicId, int? subTopicId = null)

        [NonAction]
        private List<MenuModel> GetMenuItems(int? topicId, int? subTopicId = null)
        {
            return GetMenuItems(topicId, subTopicId, false);
        }

        #endregion private List<MenuModel> GetMenuItems(int? topicId, int? subTopicId = null)

        #region private List<MenuModel> GetMenuItems(int? catId, int? subCatId, bool isNewSelected)

        [NonAction]
        private List<MenuModel> GetMenuItems(int? catId, int? subCatId, bool isNewSelected)
        {
            var menuModel = new List<MenuModel>();

            if (catId == null && subCatId == null)
            {
                if (isNewSelected == false)
                {
                    // initialize category
                    menuModel.Add(new MenuModel { MenuText = "Metadata", MenuAction = "SelectMetadata", MenuController = "Question", MenuRouteValues = null });
                    //menuModel.Add(new MenuModel { MenuText = "+", MenuAction = "CreateCategoryContent", MenuController = "Category", MenuRouteValues = null });
                }
                else
                {
                    // click on New Category
                    menuModel.Add(new MenuModel { MenuText = "Metadata", MenuAction = "SelectMetadata", MenuController = "Question", MenuRouteValues = null });
                    menuModel.Add(new MenuModel { MenuText = "New Subtopic", MenuAction = "CreateSubTopic", MenuController = "Topic", MenuRouteValues = new MenuRouteValue { ID = 0, ParentId = 0 } });
                    //menuModel.Add(new MenuModel { MenuText = "+", MenuAction = "CreateCategoryContent", MenuController = "Category", MenuRouteValues = null });
                }
            }
            else if (subCatId == null)
            {
                // catid not null
                //menuModel.Add(new MenuModel { MenuText = "Metadata", MenuAction = "SelectMetadata", MenuController = "Category", MenuRouteValues = new MenuRouteValue { ID = catId.Value } });
                //menuModel.Add(new MenuModel { MenuText = "+", MenuAction = "CreateCategoryContent", MenuController = "Category", MenuRouteValues = null });
                // Maybe never happen this case, cause we store in memory until we create category content
                menuModel.Add(new MenuModel { MenuText = "Metadata", MenuAction = "SelectMetadata", MenuController = "Question", MenuRouteValues = null });
                /*
                var catContents = CategoryQuery.GetCategoryContentByCategoryId(catId.Value, Culture.Name);

                foreach (var catContent in catContents)
                {
                    menuModel.Add(new MenuModel { MenuText = catContent.Name, MenuAction = "SelectMetadata", MenuController = "Question", MenuRouteValues = new MenuRouteValue { ID = catContent.Id } });
                }*/
            }
            else if (catId == null)
            {
                // subcatid not null
                // never happen this case
            }
            else
            {
                // both of catid and subcatid is not null
                menuModel.Add(new MenuModel { MenuText = "Metadata", MenuAction = "SelectMetadata", MenuController = "Question", MenuRouteValues = new MenuRouteValue { ID = catId.Value } });
                //TODO for each to get all category content from db and

                //menuModel.Add(new MenuModel { MenuText = "+", MenuAction = "CreateCategoryContent", MenuController = "Category", MenuRouteValues = null });
            }

            // TODO old version, will remove in future
            //if (catId == null)
            //{
            //    menuModel.Add(new MenuModel { MenuText = "Metadata", MenuAction = "SelectMetadata", MenuController = "Category", MenuRouteValues = null });
            //    //menuModel.Add(new MenuModel { MenuText = "en-GB", MenuAction = "SelectContent", MenuController = "Category", MenuRouteValues = new MenuRouteValue { ID = 1 } });
            //    menuModel.Add(new MenuModel { MenuText = "+", MenuAction = "CreateCategoryContent", MenuController = "Category", MenuRouteValues = null });
            //}
            //else
            //{
            //    menuModel.Add(new MenuModel { MenuText = "Metadata", MenuAction = "SelectMetadata", MenuController = "Category", MenuRouteValues = new MenuRouteValue { ID = catId.Value } });

            //    //List<Topic> topics = _referenceFacade.ListSubTopicTitleByTopicId(topicId.Value).ToList();
            //    //foreach (var topic in topics)
            //    {
            //        bool sel = false;

            //        if (subCatId != null)
            //            sel = 0 == subCatId.Value;

            //        menuModel.Add(new MenuModel
            //        {
            //            MenuText = "en-GB",
            //            MenuAction = "SelectContent",
            //            MenuController = "Category",
            //            MenuRouteValues = new MenuRouteValue { ID = 0, ParentId = catId.Value },
            //            IsSelected = !sel
            //        });
            //        menuModel.Add(new MenuModel
            //        {
            //            MenuText = "New Subtopic",
            //            MenuAction = "CreateSubTopic",
            //            MenuController = "Topic",
            //            MenuRouteValues = new MenuRouteValue { ID = 0, ParentId = catId.Value }
            //        });
            //    }

            //    menuModel.Add(new MenuModel
            //    {
            //        MenuText = "+",
            //        MenuAction = "CreateCategoryContent",
            //        MenuController = "Category",
            //        MenuRouteValues = new MenuRouteValue { ID = 0, ParentId = catId.Value }
            //    });
            //}

            if (isNewSelected)
            {
                menuModel[menuModel.Count - 1].IsSelected = true;
            }
            else if (!menuModel.Exists(e => e.IsSelected))
            {
                menuModel[0].IsSelected = true;
            }

            return menuModel;
        }

        #endregion private List<MenuModel> GetMenuItems(int? catId, int? subCatId, bool isNewSelected)

        #region private QuestionListViewModel Paging(int pageIndex)

        private QuestionListViewModel Paging(int pageIndex, int pageSize)
        {
            var totalPage = 0;

            //need to replace userid
            var viewModel = new QuestionListViewModel { Questions = QuestionQuery.GetPagedList(pageIndex, pageSize, 2, ref totalPage) };

            ViewData[Constants.TOTAL_PAGE] = totalPage;

            ViewData[Constants.PAGE_INDEX] = pageIndex;

            if (pageIndex > totalPage)
                return null;

            return viewModel;
        }

        #endregion private QuestionListViewModel Paging(int pageIndex)

        #endregion private
    }
}